package com.qk.interceptor;

import com.qk.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求路径
        String path = request.getServletPath();
        //判断是否为登录请求，如果是登录请求，则放行
        if (path.contains("/login")) {
            log.info("登录请求:{},放行...", path);
            return true;
        }
        //获取请求头 token
        String token = request.getHeader("token");
        //判断token是否存在，如果不存在，则返回401错误
        if (token == null || token.isEmpty()) {
            log.info("token不存在，返回401错误...");
            response.setStatus(401);
            return false;
        }
        //校验token
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("token验证失败，返回401错误...");
            response.setStatus(401);
            return false;
        }
        //放行
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("DemoInterceptor...preHandle...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("DemoInterceptor...preHandle...");
    }
}
